<?php

namespace App\Kuafu\Product\Service;

use App\Kuafu\Base\Enum\ClientEnum;
use App\Kuafu\Base\Enum\DBEnum;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Product\Enum\CodeEnum;
use App\Kuafu\Product\Enum\ProductCodeEnum;
use App\Kuafu\Product\Model\Product;
use App\Kuafu\ProductMenu\Service\ProductMenuService;
use App\Kuafu\Shop\Service\ShopService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class ProductShopService extends BaseService
{
    private $shopInfo;

    public function __construct($brandId = 0, $shopId = 0)
    {
        parent::__construct($brandId, $shopId);

        $this->shopInfo = ShopService::getShopInfo($shopId);
    }


    /**
     * 获取门店当前菜单所有底层数据
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getShopProductList()
    {
        // 获取菜单数据
        $productList = Product::getMenuProducts($this->shopInfo->menuId);

        // 获取 所有 公共自定义菜品
        $customList = Product::getMenuProductsCustom();

        // 获取 门店 自定义套餐菜品
        $customListPackage = Product::getMenuProductsPackageCustom($this->shopId);

        // 获取 店铺 定制商品信息
        $statusList  = ShopService::sGetCustomStatusList($this->shopId)->keyBy('productId');
        $customField = [
            'status',
            'showPlatform',
            'price',
            'out',
            'isMust'
        ];

        $list = $productList->merge($customList)->merge($customListPackage);

        $list = $list->each(function ($item) use ($statusList, $customField) {
            // 赋值自定义数据

            $item->out    = DBEnum::STATUS_ON;
            $item->isMust = BaseModel::SWITCH_OFF;

            // 自定义商品默认为下架
            if ($item->kind == CodeEnum::KIND_CUSTOMER) {
                $item->status = DBEnum::STATUS_DOWN;
            }

            if (empty($statusList[$item['id']])) {
                return;
            }

            foreach ($customField as $field) {
                // 单独处理
                $item->status = $statusList[$item['id']]->status;

                if (!empty($statusList[$item['id']]->$field)) {
                    $item->$field = $statusList[$item['id']]->$field;
                }
            }
        });

        return $list;
    }

    /** 公共处理
     *
     *
     * @param $listMerge
     * @param $showPlatform
     * @param $queryStatus
     * @return mixed
     */
    public function dealMapShopProductList($listMerge, $showPlatform, $queryStatus)
    {
        return $listMerge->map(function ($item) use ($showPlatform, $queryStatus) {
            // 判断是否获取所有渠道
            if ($showPlatform != ClientEnum::QUERY_CLIENT_TYPE_ALL) {
                // 小程序段过滤下架商品
                if ($showPlatform == ClientEnum::CLIENT_PRODUCT_APPLET) {
                    if ($item->status == DBEnum::STATUS_DOWN) {
                        return null;
                    }
                }

                // 不在渠道内
                if (!in_array($showPlatform, CommonService::decodeRules($item->showPlatform))) {
                    return null;
                }
            }

            // 判断是否获取所有状态
            if ($queryStatus != DBEnum::QUERY_STATUS_ALL) {
                if ($item->status != $queryStatus) {
                    return null;
                }
            }

            $item = $item->toArray();

            return [
                'productId'       => $item['id'],
                'productName'     => $item['name'],
                'productDesc'     => $item['desc'],
                'productImageUrl' => CommonService::joinImageUrl($item['imageUrl']),
                'categoryId'      => $item['category_rel']['id'] ?? 0,
                'price'           => $item['price'],
                'costPrice'       => $item['costPrice'],
                'vipPrice'        => $item['vipPrice'],
                'unit'            => $item['unit'],
                'isHot'           => $item['isHot'],
                'isRecommend'     => $item['isRecommend'],
                'status'          => $item['status'],
                'out'             => $item['out'],
                'sort'            => $item['sort'],
                'type'            => $item['type'],
                'packageList'     => $item['product_package_rel'],
                'kind'            => $item['kind'],
                'showPlatform'    => $item['showPlatform'],
                'isMust'          => $item['isMust'], // 是否必点给默认值 0
            ];
        })->filter()->values()->toArray();
    }

    public function getShopProductInfo($listMerge, $id, $showPlatform, $queryStatus = DBEnum::STATUS_ON)
    {

        $list = self::dealMapShopProductList($listMerge, $showPlatform, $queryStatus);
        $info = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                if ($item['productId'] == $id) {
                    $info = $item;
                    break;
                }
            }
        }
        return $info;
    }

    public function getOrderShopProductListWithCache()
    {
        return Cache::remember('getOrderShopProductListWithCache:' . $this->shopId, getSwitchCacheTime(60),
            function () {
                return $this->getOrderShopProductList();
            });
    }


    /**
     * 获取所有下单数据
     *
     * @return array
     */
    public function getOrderShopProductList(): array
    {
        $list       = self::getShopProductList();
        $returnList = [];
        $list->each(function ($item) use (&$returnList) {
            unset($item->categoryRel);
            $returnList[$item->id . '_' . $item->menuId] = $item;
            $item->packageList                           = $item->productPackageRel->toArray();
        })->each(function ($item) use (&$returnList) {
            if ($item->type == CodeEnum::PRODUCT_TYPE_PACKAGE) {
                foreach ($item->productPackageRel as $pkg) {
                    $pkg->name = $pkg->productName;
                    $pkg->id   = $pkg->productId;

                    // 子菜默认为上架,非估清
                    $pkg->status = DBEnum::STATUS_ON;
                    $pkg->out    = DBEnum::STATUS_ON;

                    if (!empty($returnList[$pkg->id . '_' . $pkg->menuId])) {
                        continue;
                    }
                    $returnList[$pkg->id . '_' . $pkg->menuId] = $pkg;
                }
            }

            unset($item->productPackageRel);
        });

        return collect($returnList)->toArray();
    }

    private static array $productList = [];

    /**
     * @param $shopId
     * @return array 单例获取菜品数据
     */
    public static function getProductListInstance($shopId): array
    {
        if (empty(self::$productList)) {
            ProductShopService::$productList = (new ProductShopService(0, $shopId))->getOrderShopProductListWithCache();
        }

        return ProductShopService::$productList;
    }
}
